package com.app.micaihu.custom.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;


/**
 * Created by Guo on 2016/11/11.
 */
public class VerticalRelativeLayout extends RelativeLayout {

    private int downX;
    private int downY;
    private int moveX;
    private int moveY;
    private int startMoveY;
    private int touchMoveY;
    private int totalDiffY;

    private OnTouchMoveListener mOnTouchMoveListener;


    public VerticalRelativeLayout(Context context) {
        super(context);
    }

    public VerticalRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) ev.getX();
                downY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = (int) ev.getX();
                moveY = (int) ev.getY();

                if (Math.abs(moveY - downY) > Math.abs(moveX - downX)) {

                    startMoveY = moveY;
                    return true;
                } else {

                    downX = moveX;
                    downY = moveY;
                    return super.onInterceptTouchEvent(ev);
                }


            case MotionEvent.ACTION_POINTER_DOWN://当有一个点被按住，再按下一个点
                return super.onInterceptTouchEvent(ev);

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:

                return super.onInterceptTouchEvent(ev);


        }
        return super.onInterceptTouchEvent(ev);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_MOVE:
                touchMoveY = (int) event.getY();
                if (mOnTouchMoveListener != null) {
                        mOnTouchMoveListener.smoothMove(touchMoveY - startMoveY, totalDiffY);
                }
                totalDiffY +=touchMoveY - startMoveY;

                startMoveY = touchMoveY;
                break;
            case MotionEvent.ACTION_UP:
//            case MotionEvent.ACTION_CANCEL:
                if (mOnTouchMoveListener != null) {
                    mOnTouchMoveListener.smoothUp(totalDiffY);
                    totalDiffY = 0;
                }

                break;
        }


        return super.onTouchEvent(event);
    }


    public interface OnTouchMoveListener {
        void smoothMove(int diffY, int totalDiff);

        void smoothUp(int totalDiff);
    }


    public void setOnTouchMoveListener(OnTouchMoveListener mOnTouchMoveListener) {
        this.mOnTouchMoveListener = mOnTouchMoveListener;
    }


}
